package com.aco.party.web.controller.system;

import com.aco.party.enums.MetaTypeEnum;
import com.aco.party.model.po.Meta;
import com.aco.party.model.vo.IdNamePair;
import com.aco.party.model.vo.MetaParam;
import com.aco.party.model.vo.MetaVo;
import com.aco.party.model.vo.common.DataGridEntry;
import com.aco.party.model.vo.common.Page;
import com.aco.party.model.vo.common.PageParam;
import com.aco.party.model.vo.common.Response;
import com.aco.party.service.system.MetaService;
import com.aco.party.web.command.system.EditBannerCommand;
import com.aco.party.web.command.system.EditMetaCommand;
import com.aco.party.web.validator.system.EditMetaValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;

import static com.aco.party.util.WebModelUtil.REDIRECTEDIT;

/**
 * Created by flying on 3/10/2016 0010.
 */
@Controller
@RequestMapping("/system")
public class ManageMetaController extends BaseController {
    Logger logger = LoggerFactory.getLogger(ManageMetaController.class);

    @Resource
    private MetaService metaService;

    private EditMetaValidator validator = new EditMetaValidator();

    @RequestMapping(value = {"/meta/list"}, method = RequestMethod.GET)
    public String showManagePage(HttpServletResponse response) {
        return "system/manageMetas";
    }

    @RequestMapping(value = "meta/list", method = RequestMethod.POST)
    @ResponseBody
    public Page<MetaVo> getListJson(HttpServletRequest request, DataGridEntry entry, MetaParam param) {
        Page<MetaVo> page = new Page<>();
        entry.webParamConvert();
        if(StringUtils.isEmpty(param.getType()) || "0".equals(param.getType())){
            param.setType(null);
            param.setTypes(Arrays.asList("1","2","3","4"));
        }
        List<MetaVo> list = metaService.getByPage(new PageParam(entry.getOffset(), entry.getLimit()), param);
        page.setTotal(metaService.getTotal(param));
        page.setRows(list);
        return page;
    }

    @RequestMapping(value = "/meta/edit", method = RequestMethod.GET)
    public String showEdit(HttpServletResponse response, @ModelAttribute EditMetaCommand command, Model model) {
        setAttr(model);
        if (command.getId() != null) {
            Meta po = metaService.getByPrimaryKey(command.getId());
            if (po != null)
                command.toCommand(po);
            else
                model.addAttribute("no_obj", true);
        }
        return "system/editMeta";
    }

    @RequestMapping(value = "/meta/edit", method = RequestMethod.POST)
    public String edit(Model model, @ModelAttribute EditMetaCommand command, BindingResult errors) {
        validator.validate(command, errors);
        setAttr(model);
        if (!errors.hasErrors()) {
            Meta meta = new Meta();
            command.toPo(meta);
            meta.setUpdateTime(new Date());
            metaService.update(meta);
            model.addAttribute("no_error", true);
        }
        return "system/editMeta";
    }

    @RequestMapping(value = "/meta/add", method = RequestMethod.GET)
    public String showAdd(Model model,@ModelAttribute EditMetaCommand command) {
        setAttr(model);
        command.setType("1");
        return "system/editMeta";
    }

    @RequestMapping(value = "/meta/add", method = RequestMethod.POST)
    public String add(Model model, @ModelAttribute EditMetaCommand command, BindingResult errors, RedirectAttributes attributes) {
        validator.validate(command, errors);
        setAttr(model);
        if (errors.hasErrors()) {
            return "system/editMeta";
        }
        Meta meta = new Meta();
        command.toPo(meta);
        meta.setCreateTime(new Date());
        metaService.add(meta);
        attributes.addAttribute("id", meta.getId());
        attributes.addFlashAttribute("no_error", true);
        return REDIRECTEDIT;
    }

    @RequestMapping(value = "/meta/delete", method = RequestMethod.POST)
    @ResponseBody
    public Response del(@RequestParam(required = true) Long id) {
        logger.info("删除：" + id);
        metaService.delete(id);
        return new Response();
    }

    private void setAttr(Model model){
        List<IdNamePair> types = new ArrayList<>(Arrays.asList(
                new IdNamePair(1,"产品类型"),
                new IdNamePair(2,"平台类型"),
                new IdNamePair(3,"公司类型"),
                new IdNamePair(4,"大咖类型")));
        model.addAttribute("types",types);
    }

    @RequestMapping(value = "/dictCats/list", method = RequestMethod.POST)
    @ResponseBody
    public Response showDictCats(Long id) {
        Response response = new Response();
        response.setData(metaService.getByPrimaryKey(id));
        return response;
    }

    @RequestMapping(value = "/dictCats/list", method = RequestMethod.GET)
    public String getDictCats() {
        return "system/manageDictCats";
    }

    @RequestMapping(value = "/dictCats/get")
    @ResponseBody
    public Response showDictCatsAdd(Long id) {
        Response response = new Response();
        response.setData(metaService.getByPrimaryKey(id));
        return response;
    }

    @RequestMapping(value = "/dictCats/add", method = RequestMethod.POST)
    @ResponseBody
    public Response saveDictCatsAdd(Meta meta) {
        Response response = new Response();
        if (meta == null || StringUtils.isEmpty(meta.getName())) {
            response.setStatus(-1);
            response.setMsg("请输入正确的名称！");
            return response;
        }
        meta.setType(MetaTypeEnum.词条类目.getValue());
        meta.setCreateTime(new Date());
        metaService.add(meta);
        return response;
    }

    @RequestMapping(value = "/dictCats/edit", method = RequestMethod.POST)
    @ResponseBody
    public Response saveDictCatsEdit(Meta meta) {
        Response response = new Response();
        if (meta == null || StringUtils.isEmpty(meta.getName()) || meta.getId() == null) {
            response.setStatus(-1);
            response.setMsg("参数错误！");
            return response;
        }
        meta.setType(MetaTypeEnum.词条类目.getValue());
        meta.setUpdateTime(new Date());
        metaService.update(meta);
        return response;
    }

    @RequestMapping(value = "/banner/list", method = RequestMethod.GET)
    public String showBanners(Model model,@ModelAttribute EditBannerCommand command) throws Exception {
        PropertyDescriptor[] props = null;
        props = Introspector.getBeanInfo(command.getClass(), Object.class)
                .getPropertyDescriptors();
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                String name = props[i].getName();//获取bean中的属性
                Meta meta = metaService.getByName(name);
                Method method = props[i].getWriteMethod();
                method.invoke(command,meta.getType());
            }
        }
        StringBuilder home = new StringBuilder();
        for(int i=1;i<=4;i++){
            home.append("$('#imgSel"+i+"').uploadify({\n" +
                    "                'swf': base + '/system/charisma-static/misc/uploadify.swf',\n" +
                    "                'uploader': base + '/system/uploadImg',\n" +
                    "                'fileTypeExts': '*.jpg;*.gif;*.jpeg;*.png;',\n" +
                    "                'buttonText': '请选择图片',\n" +
                    "                'fileObjName': 'file',\n" +
                    "                'multi': false,\n" +
                    "                onSelect: function (file) {//当每个文件添加至队列后触发\n" +
                    "                    if (file.size >= 2 * 1024 * 1024) {\n" +
                    "                        alert(\"选择文件不能超过2MB\");\n" +
                    "                        return false;\n" +
                    "                    }\n" +
                    "                },\n" +
                    "                onError: function (event, queueID, fileObj) {\n" +
                    "                    alert(\"文件:\" + fileObj.name + \"上传失败\");\n" +
                    "                },\n" +
                    "                onUploadSuccess: function (file, data, response) {\n" +
                    "                    data = JSON.parse(data);\n" +
                    "                    $(\"#home_banner_img_blk_"+i+" img\").remove();\n" +
                    "                    $(\"#home_banner_img_blk_"+i+"\").append(\"<img style='width:200px;' src='\" + base + \"/system/getImg?imgId=\" + data.filePath + \"'/>\");\n" +
                    "                    $(\"#home_banner_img_"+i+"\").val(data.filePath);\n" +
                    "                }\n" +
                    "            });");
        }

        StringBuilder activity = new StringBuilder();
        for(int i=1;i<=4;i++){
            activity.append("$('#imgSel_h_"+i+"').uploadify({\n" +
                    "                'swf': base + '/system/charisma-static/misc/uploadify.swf',\n" +
                    "                'uploader': base + '/system/uploadImg',\n" +
                    "                'fileTypeExts': '*.jpg;*.gif;*.jpeg;*.png;',\n" +
                    "                'buttonText': '请选择图片',\n" +
                    "                'fileObjName': 'file',\n" +
                    "                'multi': false,\n" +
                    "                onSelect: function (file) {//当每个文件添加至队列后触发\n" +
                    "                    if (file.size >= 2 * 1024 * 1024) {\n" +
                    "                        alert(\"选择文件不能超过2MB\");\n" +
                    "                        return false;\n" +
                    "                    }\n" +
                    "                },\n" +
                    "                onError: function (event, queueID, fileObj) {\n" +
                    "                    alert(\"文件:\" + fileObj.name + \"上传失败\");\n" +
                    "                },\n" +
                    "                onUploadSuccess: function (file, data, response) {\n" +
                    "                    data = JSON.parse(data);\n" +
                    "                    $(\"#activity_banner_img_blk_"+i+" img\").remove();\n" +
                    "                    $(\"#activity_banner_img_blk_"+i+"\").append(\"<img style='width:200px;' src='\" + base + \"/system/getImg?imgId=\" + data.filePath + \"'/>\");\n" +
                    "                    $(\"#activity_banner_img_"+i+"\").val(data.filePath);\n"+
                    "                }\n" +
                    "            });");
        }

        StringBuilder ad = new StringBuilder();
        for(int i=1;i<=1;i++){
            ad.append("$('#imgSel_ad_"+i+"').uploadify({\n" +
                    "                'swf': base + '/system/charisma-static/misc/uploadify.swf',\n" +
                    "                'uploader': base + '/system/uploadImg',\n" +
                    "                'fileTypeExts': '*.jpg;*.gif;*.jpeg;*.png;',\n" +
                    "                'buttonText': '请选择图片',\n" +
                    "                'fileObjName': 'file',\n" +
                    "                'multi': false,\n" +
                    "                onSelect: function (file) {//当每个文件添加至队列后触发\n" +
                    "                    if (file.size >= 2 * 1024 * 1024) {\n" +
                    "                        alert(\"选择文件不能超过2MB\");\n" +
                    "                        return false;\n" +
                    "                    }\n" +
                    "                },\n" +
                    "                onError: function (event, queueID, fileObj) {\n" +
                    "                    alert(\"文件:\" + fileObj.name + \"上传失败\");\n" +
                    "                },\n" +
                    "                onUploadSuccess: function (file, data, response) {\n" +
                    "                    data = JSON.parse(data);\n" +
                    "                    $(\"#ad_banner_img_blk_"+i+" img\").remove();\n" +
                    "                    $(\"#ad_banner_img_blk_"+i+"\").append(\"<img style='width:200px;' src='\" + base + \"/system/getImg?imgId=\" + data.filePath + \"'/>\");\n" +
                    "                    $(\"#ad_banner_img_"+i+"\").val(data.filePath);\n"+
                    "                }\n" +
                    "            });");
        }
        model.addAttribute("home",home);
        model.addAttribute("activity",activity);
        model.addAttribute("ad",ad);
        return "system/manageBanners";
    }

    @RequestMapping(value = "/banner/list", method = RequestMethod.POST)
    public String saveBanners(Model model,@ModelAttribute EditBannerCommand command) throws Exception {
        PropertyDescriptor[] props = null;
        props = Introspector.getBeanInfo(command.getClass(), Object.class)
                .getPropertyDescriptors();
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                String name = props[i].getName();//获取bean中的属性
                Meta meta = metaService.getByName(name);
                Method method = props[i].getReadMethod();
                String type = (String)method.invoke(command);
                meta.setType(type);
                meta.setUpdateTime(new Date());
                metaService.update(meta);
            }
        }
        return showBanners(model,command);
    }

}
